from sqlalchemy import create_engine, Column, Integer, String, Date, DECIMAL, BIGINT, UniqueConstraint, Index
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker


class BaseDb:
    def __init__(self, db_url : str):
        self.db_url = db_url
    def __init__(self, user : str, password : str, host : str, port : str):
        self.user = user
        self.password = password
        self.host = host
        self.port = port
        self.db_url = f"mysql+pymysql://{user}:{password}@{host}:{port}?charset=utf8mb4"
        self.engine = create_engine(self.db_url)
    def __init__(self, user : str, password : str, host : str, port : str, db_name : str):
        self.user = user
        self.password = password
        self.host = host
        self.port = port
        self.db_name = db_name
        self.db_url = f"mysql+pymysql://{user}:{password}@{host}:{port}?charset=utf8mb4"
        self.engine = create_engine(self.db_url)
        self.create_db(db_name)
        # try:
        #     with self.engine.connect() as conn:
        #         print("数据库连接成功")
        # except Exception as e:
        #     print(f"数据库连接失败: {e}")
    
    def create_db(self, db_name):
        with self.engine.connect() as conn:
            conn.execute(f"CREATE DATABASE IF NOT EXISTS {db_name} DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;")
            print(f"数据库 {db_name} 创建成功")
        
        # 2. 连接到数据库
        self.db_url = f"mysql+pymysql://{self.user}:{self.password}@{self.host}:{self.port}/{db_name}?charset=utf8mb4"
        self.engine = create_engine(self.db_url, echo=False)
    
    def drop_db(self):
        with self.engine.connect() as conn:
            conn.execute(f"DROP DATABASE IF EXISTS {self.db_name};")
            print(f"数据库 {self.db_name} 删除成功")

if __name__ == "__main__":
    db = BaseDb("root", "123456", "localhost", "3306", "test")
    db.drop_db()
    # db.create_db("test")